<?php
/**
 * Prado Portal.
 *
 * @author Steen Rabol <steen.rabol@gmail.com>
 * @link http://www.pradoportal.dk/
 * @copyright Copyright &copy; 2006,2007,2008 Steen Rabol
 * @license http://www.pradoportal.dk
 * @version $Id: PageMan.php 360 2010-02-03 08:07:12Z steen.rabol@gmail.com $
 *
 */

Prado::using('Application.Common.Data.PortalPageRecord');

class PageMan extends PortalAdminPage
{
	public function getDataRows($offset, $rows)
	{
		return $this->DataAccess->createCommand("select * from tblpages order by displayname,path LIMIT $offset,$rows")->query();
	}

	public function onLoad($param)
	{
		parent::onLoad($param);
		$this->setAdminPageTitle('Pages');

		if(!$this->isPostBack)
		{
			$this->checkDisplayName();
			$this->PagesGrid->VirtualItemCount	= $this->RowCount;
			$this->PagesGrid->DataSource		= $this->getDataRows(0,$this->PagesGrid->PageSize);
			$this->PagesGrid->dataBind();
		}
	}

	protected function getRowCount()
    {
        return $this->DataAccess->createCommand("select count(id) from tblpages")->queryScalar();
    }

	public function onItemCommand($sender, $param)
	{
		switch($param->CommandName)
		{
			case "view":
				$Id		= $this->PagesGrid->DataKeys[$param->Item->ItemIndex];
				$page 	= $this->DataAccess->createCommand("select fullpath from tblpages where id =$Id")->queryScalar();
				$this->gotoPage($page, array("PageMode" => 1));
				break;

			case "MoveUp":
				$this->MoveUp($this->PagesGrid->DataKeys[$param->Item->ItemIndex]);
				break;

			case "MoveDown":
				$this->MoveDown($this->PagesGrid->DataKeys[$param->Item->ItemIndex]);
				break;

			case "RemoveItem":
				$this->RemoveItem($this->PagesGrid->DataKeys[$param->Item->ItemIndex]);
				break;
		}
	}

	public function changePage($sender, $param)
	{
		$this->PagesGrid->CurrentPageIndex	= $param->NewPageIndex;
        $offset								= $param->NewPageIndex*$this->PagesGrid->PageSize;
        $this->PagesGrid->DataSource		= $this->getDataRows($offset,$this->PagesGrid->PageSize);
        $this->PagesGrid->dataBind();
	}

	public function pagerCreated($sender, $param)
	{
		$param->Pager->Controls->insertAt(0, Prado::localize('Page').': ');
	}

	public function editItem($sender, $param)
	{
		$this->PagesGrid->EditItemIndex	= $param->Item->ItemIndex;
        $offset							= $this->PagesGrid->CurrentPageIndex * $this->PagesGrid->PageSize;
        $this->PagesGrid->DataSource	= $this->getDataRows($offset,$this->PagesGrid->PageSize);
        $this->PagesGrid->dataBind();
	}

	public function getDropDownData()
	{
		$pl		= array();
		$pl[]	= array("name" => Prado::localize("Select"), "id" => "0");

		foreach(PortalUtil::getAvailablePortalLayouts() as $l)
		{
			$pl[] = array("name" => $l['name'], "id" => $l['id']);
		}

		return $pl;
	}

	public function getYesNoData()
	{
		$pl		= array();
		$pl[]	= array("name" => Prado::localize("No"), "id" => 0);
		$pl[]	= array("name" => Prado::localize("Yes"), "id" => 1);
		return $pl;
	}

	public function saveItem($sender, $param)
	{
		$item					= $param->Item;
		$pageId					= $this->PagesGrid->DataKeys[$item->ItemIndex];
		$pageRecord				= $this->DataAccess->createCommand("select * from tblpages where id=$pageId")->queryRow();
		$pageRecord['active']	= TPropertyValue::ensureInteger($item->Cells[2]->PageStatus->SelectedValue);
		$displayname			= $item->DisplayName->TextBox->Text;
		$layoutname				= $item->Cells[3]->DropDown->SelectedValue;
		$modified				= time();
		$locked					= TPropertyValue::ensureInteger($item->Cells[4]->PageLocked->SelectedValue);

		if($locked != 0)
		{
			$lockedby	= $this->User->Id;
			$lockedtime	= time();
		}
		else
		{
			$lockedby	= 0;
			$lockedtime	= 0;
		}

		$sql = "update tblpages set layoutname='$layoutname',active=" . $pageRecord['active'] . ",modified=$modified,displayname='$displayname',locked='$locked',lockedby='$lockedby',lockedtime='$lockedtime' where id=" . $pageRecord['id'];

		try
		{
			$this->DataAccess->createCommand($sql)->execute();
		}
		catch(Exception $e)
		{
			$this->reportError(1,$e->getMessage());
		}

		$this->PagesGrid->EditItemIndex		= -1;
		$this->PagesGrid->SelectedItemIndex	= -1;
        $offset								= $this->PagesGrid->CurrentPageIndex * $this->PagesGrid->PageSize;
        $this->PagesGrid->DataSource		= $this->getDataRows($offset,$this->PagesGrid->PageSize);
        $this->PagesGrid->dataBind();
	}

	public function cancelItem($sender, $param)
	{
		$this->PagesGrid->EditItemIndex		= -1;
		$this->PagesGrid->SelectedItemIndex	= -1;
        $offset								= $this->PagesGrid->CurrentPageIndex * $this->PagesGrid->PageSize;
        $this->PagesGrid->DataSource		= $this->getDataRows($offset,$this->PagesGrid->PageSize);
        $this->PagesGrid->dataBind();
	}

	public function deleteItem($sender, $param)
	{
		$item		= $param->Item;
		$Id			= $this->PagesGrid->DataKeys[$item->ItemIndex];
		$pagerow	= $this->DataAccess->createCommand("select * from tblpages where id=$Id")->queryRow();
		$sql		= "delete from tblpages where id=$Id";
		$this->DataAccess->createCommand($sql)->execute();

		// delete php file
		if(file_exists($this->Service->BasePath . "/" . $pagerow['name'] . ".php"))
		{
			@unlink($this->Service->BasePath . "/" . $pagerow['name'] . ".php");
		}

		// delete page file
		if(file_exists($this->Service->BasePath . "/" . $pagerow['name'] . ".page"))
		{
			@unlink($this->Service->BasePath . "/" . $pagerow['name'] . ".page");
		}

		// delete references to this page
		$this->DataAccess->createCommand("delete from tblpagecontent where pagename = '{$pagerow['name']}'")->execute();
		$this->DataAccess->createCommand("delete from tbllxlistmenuportlet where pagename = '{$pagerow['name']}'")->execute();
		//$this->DataAccess->createCommand("delete from tbljscookmenuitem where pagename = '{$pagerow['name']}'")->execute();
		$this->DataAccess->createCommand("delete from tblsitemenuitem where page = '{$pagerow['name']}'")->execute();

		$this->PagesGrid->VirtualItemCount	= $this->RowCount;
        $offset								= $this->PagesGrid->CurrentPageIndex * $this->PagesGrid->PageSize;
        $this->PagesGrid->DataSource		= $this->getDataRows($offset,$this->PagesGrid->PageSize);
        $this->PagesGrid->dataBind();
	}

	public function itemCreated(&$sender, $param)
	{
		$item = &$param->Item;

		if($item->ItemType === 'EditItem')
		{
			$item->DisplayName->TextBox->Columns=45;
		}

		if($item->ItemType === 'Item' || $item->ItemType === 'AlternatingItem' || $item->ItemType === 'EditItem')
		{
			// add an aleart dialog to delete buttons
			$item->DeleteColumn->Button->Attributes->onclick	= 'if(!confirm(\'' . Prado::localize('This will also delete the page file\nAre you sure?').'\')) return false;';
			$item->ViewColumn->Button->CommandParameter			= $this->PagesGrid->DataKeys[$item->ItemIndex];
		}
	}

	public function ValidateLayoutName($layoutname)
	{
		$retval		= ' ';
		$first		= true;
		$validData	= $this->getDropDownData();

		if($validData)
		{
			foreach($validData as $vvalue)
			{
				if($first)
				{
					$retval = $vvalue['id']; //In case we don't find our wanted we return a valid on :-)
					$first	= false;
				}

				if($vvalue['id'] == $layoutname)
				{
					return $layoutname;
				}
			}
		}

		return $retval;
	}

	private function MoveUp($p_id)
	{
		$sql = "select * from tblpages where id=$p_id";
		$row = $this->DataAccess->createCommand($sql)->queryRow();

		if($row !== null)
		{
			$sql = "update tblpages set displayorder=displayorder -1.001 where id=$p_id";
			$this->DataAccess->createCommand($sql)->execute();
			$this->RenumDisplayOrder();
			$this->RenumDisplayOrder(1);
		}

        $offset							= $this->PagesGrid->CurrentPageIndex * $this->PagesGrid->PageSize;
        $this->PagesGrid->DataSource	= $this->getDataRows($offset,$this->PagesGrid->PageSize);
        $this->PagesGrid->dataBind();
	}

	private function MoveDown($p_id)
	{
		$sql	= "select * from tblpages where id=$p_id";
		$row	= $this->DataAccess->createCommand($sql)->queryRow();

		if($row !== null)
		{
			$sql	= "update tblpages set displayorder=displayorder +1.001 where id=$p_id";
			$this->DataAccess->createCommand($sql)->execute();
			$this->RenumDisplayOrder();
			$this->RenumDisplayOrder(1);
		}

        $offset							= $this->PagesGrid->CurrentPageIndex * $this->PagesGrid->PageSize;
        $this->PagesGrid->DataSource	= $this->getDataRows($offset,$this->PagesGrid->PageSize);
        $this->PagesGrid->dataBind();
	}

	private function RenumDisplayOrder($p_startat = 999.000)
	{
		$newdisplayorder	= $p_startat;
		$sql				= "select * from tblpages order by displayorder";
		$rows				= $this->DataAccess->createCommand($sql)->query();

		if($rows)
		{
			foreach($rows as $row)
			{
				$sql = "update tblpages set displayorder=$newdisplayorder where id='" . $row["id"] . "'";
				$this->DataAccess->createCommand($sql)->execute();
				$newdisplayorder++;
			}
		}
	}

	public function LockedByUser($uid)
	{
		return $this->DataAccess->createCommand("select name from tblusers where id=$uid")->queryScalar();
	}

	public function sortDataGrid($sender, $param)
	{
		$this->LogGrid->DataSource = $this->sortData($this->Data, $param->SortExpression);
		$this->LogGrid->dataBind();
	}

	protected function sortData($data, $key)
	{
		$compare = create_function('$a,$b', 'if ($a["'.$key.'"] == $b["'.$key.'"]) {return 0;}else {return ($a["'.$key.'"] > $b["'.$key.'"]) ? 1 : -1;}');
		usort($data, $compare);
		return $data;
	}
/*
	public function RemoveItem($id)
	{
		PortalPageRecord::finder()->deleteByPk($id);

		$this->PagesGrid->VirtualItemCount	= $this->RowCount;
        $offset								= $this->PagesGrid->CurrentPageIndex * $this->PagesGrid->PageSize;
        $this->PagesGrid->DataSource		= $this->getDataRows($offset,$this->PagesGrid->PageSize);
        $this->PagesGrid->dataBind();
	}
*/
	private function checkDisplayName()
	{
		$pages	= PortalPageRecord::finder()->findAll("displayname=''");

		if($pages && is_array($pages) && count($pages) >0)
		{
			foreach($pages as $page)
			{
				$page->displayname	= $page->name;
				$page->save();
			}
		}
	}
}
?>